<?php

namespace app\common\model;

use think\Model;


class Hospitalappoint extends Model
{

    

    

    // 表名
    protected $name = 'hospital_appointment';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    public static function addlivejobs($jobs,$live_id,$hospital_id,$week_name,$week_days)
    {
        $hastime=self::where(['time_id'=>$live_id])->select();


        $week_days=explode(',',$week_days);
        $week_name=explode(',',$week_name);
        foreach($hastime as $k5=>$v5) {
            $qhas = 0;

            foreach ($week_days as $k4=>$v4){
                foreach ($jobs as $k => $v) {
                    if(isset($v['time_id'])){
                        if ($v['time_id']==$v5['time_id']&&$v5['hospital_id']==$hospital_id&&$v['endtime']==$v5['endtime']&&$v['startime']==$v5['startime']&&$v5['week_days']==$v4) {
                            $qhas = 1;
                            $jobs[$k]['live_job_id'] = $v5['id'];
                        }
                    }


                }
            }


            if ($qhas == 0) {

                self::destroy(['id' => $v5['id']]);

            }

        }

        foreach ($jobs as $k => $v) {


            if (isset($v['live_job_id'])) {
                //判断当前是否存在对应时间
                $livejob = self::where(['id' => $v['live_job_id']])->find();
                if ($livejob) {

                    $livejob->hospital_id = $hospital_id;
                    $livejob->updatetime = time();
                    $livejob->save();
                }
            } else {
                $msaves=[];
                foreach ($week_days as $k6=>$v6) {
                    $msaves[] = [
                        'hospital_id' => $hospital_id,
                        'endtime' => $v['endtime'],
                        'startime' => $v['startime'],
                        'week_name' => $week_name[$k6],
                        'time_id' => $live_id,
                        'week_days' => $v6,
                        'createtime' => time(),
                    ];
                }
                $res=self::insertAll($msaves);

            }


        }



    }
    







    public function hospital()
    {
        return $this->belongsTo('Hospital', 'hospital_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function time()
    {
        return $this->belongsTo('app\common\model\hospital\appointment\Time', 'time_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
